package com.jt.chapter02.config;

import com.jt.chapter02.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @author jiang tao
 * @date 2022/1/7
 * @description:
 **/
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = (String) authentication.getPrincipal(); //拿到username
        String password = (String) authentication.getCredentials(); //拿到password

        UserDetails userDetails = myUserDetailsService.loadUserByUsername(userName);
        if (userName.equals(userDetails.getUsername()) && password.equals(userDetails.getPassword())) {
            return authentication;
        }
        /*验证不通过*/
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {

        return true;
    }

}
